// app/admin/policies/page.tsx (서버 컴포넌트)
import { Metadata } from 'next'
import { eq, desc } from 'drizzle-orm'
import db from '@/db/db'
import { policyVersions } from '@/db/schema'
import { PolicyPageClient } from '@/components/polices/policy-page-client'
import { useTranslation } from "@/i18n"

export const metadata: Metadata = {
  title: '정책 관리 | eVCP Admin',
  description: '개인정보 처리방침 및 이용약관 관리'
}

// 정책 데이터 조회 함수
async function getPoliciesData() {
  try {
    // 현재 활성 정책들 (모든 locale)
    const currentPolicies = await db
      .select()
      .from(policyVersions)
      .where(eq(policyVersions.isCurrent, true))
      .orderBy(policyVersions.policyType, policyVersions.locale)

    // 전체 정책 히스토리
    const allPolicies = await db
      .select()
      .from(policyVersions)
      .orderBy(desc(policyVersions.createdAt))

    // locale별로 정책 타입별 그룹화
    const policiesByLocaleAndType = {
      ko: {
        privacy_policy: allPolicies.filter(p => p.policyType === 'privacy_policy' && p.locale === 'ko'),
        terms_of_service: allPolicies.filter(p => p.policyType === 'terms_of_service' && p.locale === 'ko')
      },
      en: {
        privacy_policy: allPolicies.filter(p => p.policyType === 'privacy_policy' && p.locale === 'en'),
        terms_of_service: allPolicies.filter(p => p.policyType === 'terms_of_service' && p.locale === 'en')
      }
    }

    // 현재 정책 맵 (locale별)
    const currentPolicyMap = {
      ko: {},
      en: {}
    }
    currentPolicies.forEach(policy => {
      currentPolicyMap[policy.locale][policy.policyType] = policy
    })

    return {
      currentPolicies: currentPolicyMap,
      allPolicies: policiesByLocaleAndType,
      stats: {
        totalVersions: allPolicies.length,
        koVersions: {
          privacy: policiesByLocaleAndType.ko.privacy_policy.length,
          terms: policiesByLocaleAndType.ko.terms_of_service.length
        },
        enVersions: {
          privacy: policiesByLocaleAndType.en.privacy_policy.length,
          terms: policiesByLocaleAndType.en.terms_of_service.length
        },
        lastUpdate: allPolicies[0]?.createdAt || null
      }
    }
  } catch (error) {
    console.error('Failed to fetch policies:', error)
    return {
      currentPolicies: { ko: {}, en: {} },
      allPolicies: { 
        ko: { privacy_policy: [], terms_of_service: [] }, 
        en: { privacy_policy: [], terms_of_service: [] } 
      },
      stats: { 
        totalVersions: 0, 
        koVersions: { privacy: 0, terms: 0 },
        enVersions: { privacy: 0, terms: 0 },
        lastUpdate: null 
      }
    }
  }
}


export default async function PoliciesPage(props: { params: Promise<{ lng: string }> }) {
  const { lng } = await props.params

  const data = await getPoliciesData()

  return <PolicyPageClient data={data as any} lng={lng} />
}
